//让node能连接上MySQL
const mysql = require('mysql');
const config = require('../config/index.js')

// 创建线程池
const pool =mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password : config.database.PASSWORD,
  database : config.database.DATABASE,
  port : config.database.PORT
})

// 连接数据库，执行sql语句
const allService = {
  query : function (sql,values) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err,connection)=>{ //连接数据库
        
        if (err) {
          console.log(err);
          reject(err)
        }else {//连接成功
          console.log(12312321312);
          connection.query(sql,values,(err,rows)=>{//执行sql语句
            if (err) {
              reject(err)
            }else { // sql 语句执行成功
              resolve(rows)
            }
            connection.release()//断开连接
          })
        } 

      })
    })
  }
}

//登录 
const userLogin = (username, password) => {
  let _sql = `select * from users where username="${username}" and password="${password}";`
  return allService.query(_sql)
}
//查找
const userFind = (username) => {
  let _sql = `select *  from users where username="${username}";`
  return allService.query(_sql)
}
//注册
const userRegister = (values) => {
  let _sql = `insert into users set username=?,password=?,nickname=?;`
  return allService.query(_sql,values)
}
//查找对应文章列表
const findeNoteListByType = (note_type) => {
  let _sql = `select * from note where note_type="${note_type}";`
  return allService.query(_sql)
}
//查找id对应的文章
const findeNoteListById = (id) => {
  let _sql = `select * from note where id="${id}";`
  return allService.query(_sql)
}
//发布笔记
const publishNote = (values) => {
  let _sql = `insert into note set userId=?,title=?,note_type=?,note_content=?,c_time=?,m_time=?,head_img=?,nickname=?;`
  return allService.query(_sql,values)
}

module.exports = {
  userLogin,
  userFind,
  userRegister,
  findeNoteListByType,
  findeNoteListById,
  publishNote
}
